using Decisions.HL7.Message;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace Decisions.HL7.DataTypes
{
    public class DT : AbstractDataType
    {

        public DateTime? Value { get; set; }

        private static string[] formatParts = new[]
            {
                "yyyy",
                "MM",
                "dd"
            };

        // "yyyy".Length
        internal const int YEAR_PRECISION = 4;

        // "yyyyMM".Length
        internal const int MONTH_PRECISION = 6;

        // "yyyyMMdd".Length 
        internal const int DAY_PRECISION = 8;

        public override void Parse(string parseableText, HL7ParserOptions options, string dataName, char? whichSep)
        {

            if (string.IsNullOrWhiteSpace(parseableText)) Value = null;
            else
            {
                // Parsing date

                string format = string.Empty;
                int i = 0;
                do
                {
                    format = format + formatParts[i];

                    i++;

                    if (i >= formatParts.Length) break;
                }
                while (parseableText.Length > format.Length);

                DateTime resultValue;
                if (DateTime.TryParseExact(parseableText, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out resultValue))
                {
                    Value = resultValue;
                }
                else
                {
                    Value = null;
                    throw new Exception(dataName + " could not be parsed as a date");
                }
            }
        }


        public override string GetER7(HL7ParserOptions options)
        {
            // Write date out sensibly.
            return (Value != null && Value.Value != null) ? Value.Value.ToString("yyyyMMdd") : null;
        }
    }
}
